/*
 ============================================================================
 Page	     : 238-239
 Name        : menuette.c
 Date	     : 20210404
 Author      : Hbue 18060333
 Copyright   : Your copyright notice
 Description : 菜单程序
 ============================================================================
 */

#include <stdio.h>
char get_choice(void);
char get_first(void);
int get_int(void);
void count(void);
int main(void)
{
	int choice = 0;
	void count(void);

	while((choice = get_choice()) != 'q')
	{
		switch(choice)
		{
			case 'a':
				printf("Buy low, sell high.\n");
				break;
			case 'b':
				putchar('\a');		/* ANSI */
				break;
			case 'c':
				count();
				break;
			default:
				printf("Program error!\n");
				break;
		}
	}
	printf("Bye.\n");

	return 0;
}

void count(void)
{
	printf("Count how far? Enter an integer:\n");
	int n = get_int();
	for(int i = 1;i <= n;i++)
	{
		printf("%d\n", i);
	}
	while(getchar() != '\n')
	{
		continue;
	}
}

char get_choice(void)
{
	printf("Enter the letter of your choice:\n");
	printf("a. advice         b.bell\n");
	printf("c. count     	  q.quit\n");
	int ch = get_first();
	while((ch < 'a' || ch > 'c') && ch != 'q')
	{
		printf("Please respond with a, b, c, or q.\n");
		ch = get_first();
	}

	return ch;
}

char get_first(void)
{
	int ch = 0;

	ch = getchar();
	while(getchar() != '\n')
	{
		continue;
	}

	return ch;
}

int get_int(void)
{
	char ch = 0;
	int input = 0;

	while(scanf("%d", &input) != 1)
	{
		while((ch = getchar()) != '\n')
		{
			putchar(ch);				// 处理错误输出
		}
		printf(" is not an integer.\n");
		printf("Please enter an integer value, such as 25, -178, or 3: ");
	}

	return input;
}

